<?php

namespace app\admin\model\service;

use app\admin\model\AdminUserModel;
use app\admin\model\product\Category as ProductCategory;
use app\admin\model\env\Category as EnvCategory;
use app\admin\model\Area;
use app\admin\model\relation\ServiceAgentAreaRelation;
use app\admin\model\relation\ServiceAgentEnvCategoryRelation;
use app\admin\model\relation\ServiceAgentProductCategoryRelation;
use app\admin\model\ReportModel;
use think\Model;

class Agent extends Model
{


    // 表名
    protected $name = 'service_agent';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [

    ];

    public function productCategory()
    {
        return $this->belongsToMany(
            ProductCategory::class,
            "service_agent_product_category_relation",
            "product_category_id",
            "service_agent_id"
        );
    }

    public function envCategory()
    {
        return $this->belongsToMany(
            EnvCategory::class,
            "service_agent_env_category_relation",
            "env_category_id",
            "service_agent_id"
        );
    }

    public function area()
    {
        return $this->belongsToMany(
            Area::class,
            "service_agent_area_relation",
            "area_id",
            "service_agent_id"
        );
    }

    public function updateAreaRelation($id, $area = [])
    {
        $data = [];
        foreach ($area as $a) {
            $data[] = [
                'service_agent_id' => $id,
                'area_id' => $a
            ];
        }
        $this->clearAreaRelation($id);
        (new ServiceAgentAreaRelation())->insertAll($data);
    }

    public function clearAreaRelation($id)
    {
        (new ServiceAgentAreaRelation())->where('service_agent_id', $id)->delete();
    }

    public function updateProductCategoryRelation($id, $category = [])
    {
        $data = [];

        foreach ($category as $a) {
            if ($a) {
                $data[] = [
                    'service_agent_id' => $id,
                    'product_category_id' => $a
                ];
            }

        }

        $this->clearProductCategoryRelation($id);
        $data && (new ServiceAgentProductCategoryRelation())->insertAll($data);
    }

    public function clearProductCategoryRelation($id)
    {
        (new ServiceAgentProductCategoryRelation())->where('service_agent_id', $id)->delete();
    }

    public function updateEnvCategoryRelation($id, $category = [])
    {
        $data = [];

        foreach ($category as $a) {
            if ($a) {
                $data[] = [
                    'service_agent_id' => $id,
                    'env_category_id' => $a
                ];
            }

        }

        $this->clearEnvCategoryRelation($id);
        $data && (new ServiceAgentEnvCategoryRelation())->insertAll($data);
    }
    public function updateUserId($id, $userId){
        $this->update(["user_id"=>$userId],["id"=>$id]);
    }
    public  function  updateDetails($id, $details){
        $AgentDetails=AgentDetails::where(['service_agent_id'=>$id])->find();
        if($details){
            if(!$AgentDetails){
                $details['service_agent_id'] =$id;
                AgentDetails::create($details) ;
            }else{
                AgentDetails::where(['service_agent_id'=>$id])->update($details);
            }
        }else{
            if($AgentDetails){
                AgentDetails::where(['service_agent_id'=>$id])->delete();
            }
        }
        return true;
    }

    public   function   updateAdminUser($id,$params){
//        $pwd= md5(trim($params['password']).'vueadmin');
        $pwd=md5(trim($params['password']).'vueadmin');  //vueadmin;
        if($id){
            $adminUser= AdminUserModel::where(['agent_id'=>$id])->find();
            if(!empty($adminUser)){
//                $adminUser->user=$params['phone'];
//                $adminUser->pwd=md5(trim($params['password']).'vueadmin');
                AdminUserModel::where(['user_id'=>$adminUser['user_id']])->update(['user'=>$params['phone'],'pwd'=>$pwd]);
            }else{
                AdminUserModel::create(
                    [
                        'name'=>$params['name'],
                        'user'=>$params['phone'],
                        'role_id'=>$params['type']  == 1 ? 51: 52,
                        'note'=>$params['type']  == 1 ?  '代理': '服务站',//这个地方还得改
                        'status'=>1,
                        'create_time'=>time(),
                        'agent_id'=>$id,
                        'pwd'=>$pwd,
                    ]
                );
            }
        }else{

            AdminUserModel::create(
                [
                    'name'=>$params['name'],
                    'user'=>$params['phone'],
                    'role_id'=>$params['type']  == 1 ? 51: 52,
                    'note'=>$params['type']  == 1 ?  '代理': '服务站',//这个地方还得改
                    'status'=>1,
                    'create_time'=>time(),
                    'agent_id'=>$id,
                    'pwd'=>$pwd,
                ]
            );
        }

        return true;
    }

    public function clearEnvCategoryRelation($id)
    {
        (new ServiceAgentEnvCategoryRelation())->where('service_agent_id', $id)->delete();
    }

    public function serviceAgentDetails()
    {
        return $this->hasOne(
            AgentDetails::class,
            "service_agent_id",
            "id"
        );
    }

    public  function adminUser(){
        return $this->belongsTo(AdminUserModel::class,'id','agent_id');
    }


}
